package com.apesay.service.auth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apesay.exception.ServiceException;
import com.apesay.service.base.ClientService;
import com.apesay.utils.Constant;
import com.apesay.utils.MongoCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PermissionService {
	@Autowired
	private ClientService clientService;
	@Autowired
	private RoleService roleService;
	
	public JSONArray getPermissionsByUserId(String userId)  {
		JSONArray roleArray=roleService.getRolesByUserId(userId);
		JSONArray permissionArray=new JSONArray();
		for(int i=0;i<roleArray.size();i++){
			JSONObject roleObject= clientService.getObjectById(Constant.model_backend_role,roleArray.getString(i));
			if(roleObject!=null){
				JSONObject roleJsonObject=roleObject.getJSONObject(Constant.RESULT);
				if(roleJsonObject!=null&&roleJsonObject.getJSONArray("permissions")!=null){
					for(int j=0;j<roleJsonObject.getJSONArray("permissions").size();j++){
						JSONObject permissionObject= clientService.getObjectById(Constant.model_backend_permission,roleJsonObject.getJSONArray("permissions").getString(j));
						if(permissionObject!=null&&permissionObject.getJSONObject(Constant.RESULT)!=null){
							if(!permissionArray.contains(permissionObject.getJSONObject(Constant.RESULT))){
								permissionArray.add(permissionObject.getJSONObject(Constant.RESULT));
							}
						}
					}
				}
			}
		}
		return permissionArray;
	}
	public JSONArray getMenusById(String userId) {
		JSONArray roleArray=roleService.getRolesByUserId(userId);
		JSONArray jsonArray  = new JSONArray();
		for (Object object : roleArray) {
			String objectId = (String) object;
			JSONObject roleObject= clientService.getObjectById(Constant.model_backend_role,objectId);
			if(roleObject!=null){
				JSONObject roleJsonObject=roleObject.getJSONObject(Constant.RESULT);
				if(roleJsonObject!=null&&roleJsonObject.getJSONArray("menus")!=null){
					JSONArray menus = roleJsonObject.getJSONArray("menus");
					JSONObject query = new JSONObject();
					JSONObject in = new JSONObject();
					in.put(MongoCondition.IN.getVal(), menus);
					query.put(Constant.OBJECTID, in);
					JSONObject permissionObject= clientService.find(query.toJSONString(), "{}", "{}",
							Constant.model_backend_menu, 0, Integer.MAX_VALUE);
					jsonArray.addAll(permissionObject.getJSONObject(Constant.RESULT).getJSONArray(Constant.RESULTS));
				}
			}
		}
		return jsonArray;
	}
}
